﻿using System.Xml;
using Xom.Attributes;

namespace Xom.Utilities
{
    //todo description
    public static class XmlUtility
    {
        public static XmlNode GetNodeByName(XmlNode rootNode, string name, bool toLowerCase)
        {
            if (toLowerCase) name = name.ToLower();

            foreach (XmlNode child in rootNode.ChildNodes)
            {
                string childName = child.Name;
                if (toLowerCase) childName = childName.ToLower();

                if (childName == name) return child;

                foreach (XmlNode childChilds in child.ChildNodes)
                {
                    string childChildName = childChilds.Name;
                    if (toLowerCase) childChildName = childChildName.ToLower();

                    if (childChildName == name) return childChilds;

                    XmlNode result = GetNodeByName(childChilds, name, toLowerCase);
                    if (result != null) return result;
                }
            }

            return null;
        }

        public static XmlNode GetAttributeByName(XmlNode rootNode, string name, bool toLowerCase)
        {
            if (toLowerCase) name = name.ToLower();
            if (rootNode.Attributes != null)
            {
                foreach (XmlAttribute attribute in rootNode.Attributes)
                {
                    string attributeName = attribute.Name;
                    if (toLowerCase) attributeName = attributeName.ToLower();

                    if (attributeName == name) return attribute;
                }
            }

            foreach (XmlNode child in rootNode.ChildNodes)
            {
                XmlNode result = GetAttributeByName(child, name, toLowerCase);
                if (result != null) return result;
            }

            return null;
        }

        public static XmlNode GetElementByName(XmlNode rootNode, XomBinding binding, bool toLowerCase)
        {
            if (binding.IsAttribute)
            {
                return GetAttributeByName(rootNode, binding.XmlName, toLowerCase);
            }
            else
            {
                return GetNodeByName(rootNode, binding.XmlName, toLowerCase);
            }
        }
    }
}
